<?php

class TermService extends FServiceBase
{    
    /**
    * Get a Term model given its ID
    * 
    * @param int id Term ID
    * @return FServiceModel
    */
    public function get($params){
        $model = Term::model()->findByPk($this->getParam($params, 'id',0));
        if (! $model)
            $this->result->fail(ERROR_INVALID_DATA, Yii::t('Admin.Term','Invalid ID.'));
        $this->result->processed('model', $model);
        return $this->result;
    }
    
    public function save($params) {
        /**
        * @var CModel
        */
        $model = $this->getModel($params['Term'],'Term');
        $this->result->processed('model', $model);
        
        $model->setScenario('single_save');
        if (! $model->validate())
            $this->result->fail(ERROR_INVALID_DATA, Yii::t('Admin.Term', 'Submitted data is missing or invalid.'));
        elseif ($this->getParam($params, 'validateOnly',0) == TRUE)
            return $this->result;
        if ($model->save(false))
        {
            if ($model->parentId)
            {
                $relation = TermHierarchy::model()->findByAttributes(array('term_id'=>$model->id));
                if (!is_object($relation))
                {
                    $relation = new TermHierarchy;
                    $relation->term_id = $model->id;
                }
                $relation->parent_id = $model->parentId;
                if (!$relation->save())
                {
                    Yii::log(CVarDumper::dumpAsString($relation->getErrors()), CLogger::LEVEL_ERROR);
                }
            }
        }
        else
        {
            $this->result->fail(ERROR_HANDLING_DB, Yii::t('Core.Term','Error while saving submitted data into database.'));
        }
        
        return $this->result;
    }


    public function delete($params) {
        $ids = $this->getParam($params, 'ids', array());
        if ($ids == 0) {
            return $this->result->fail(ERROR_INVALID_DATA, Yii::t('Admin.Term','Invalid ID.'));
        }
      
        if (!is_array($ids)) $ids = array($ids);
        foreach($ids as $id) {
            $model = Term::model()->findByPk($id);
            if (is_object($model))
            {
                //upgrade children 1 level
                $parentId = 0;//root
                $parent = TermHierarchy::model()->findByAttributes(array('term_id'=>$id));
                if (is_object($parent) && $parent->parent_id)
                    $parentId = $parent->parent_id;
                
                //find next ordering
                $nextOrder = $this->findNextOrder($parentId, $model);
                
                $criteria = new CDbCriteria;
                $criteria->compare('t.parent_id', $id);
                if (TermHierarchy::model()->exists($criteria))
                {
                    $criteria->join = 'INNER JOIN '.SITE_TABLE_PREFIX.'taxonomy_term ter ON ter.id = t.term_id';
                    $criteria->order = 'ter.ordering';
                    $children = TermHierarchy::model()->findAll($criteria);
                    foreach ($children as $child)
                    {
                        $nextOrder++;
                        Term::model()->updateByPk($child->term_id, array('ordering'=>$nextOrder));
                        if ($parentId)
                        {
                            /** @var TermHierarchy */
                            $child->saveAttributes(array('parent_id'=>$parentId));
                        }
                        else
                            $child->delete();
                    }
                }
                TermHierarchy::model()->deleteAllByAttributes(array('term_id'=>$model->id));
            }
            try {
                $model->delete();
            } catch (CDbException $ex) {
                $this->result->fail(ERROR_HANDLING_DB, $ex->getMessage());
            }
        }
        return $this->result;
    }
    
    public function bulkCreate($params)
    {
        $catNames = $this->getParam($params, 'names', array());
        $parentId = $this->getParam($params, 'parentId', '');
        $v_id = $this->getParam($params, 'vocabularyId', '');
        if ($v_id=='')
            return $this->result->fail(ERROR_INVALID_DATA, 'Missing Vocabulary Id');
        
        foreach($catNames as $catName)
        {
            $catName = trim($catName);
            if ($catName=='') continue;
            $model = new Term('single_save');
            $model->v_id = $v_id;
            $model->name = $catName;
            $model->alias = Utility::createAlias($model,$model->name);
            $model->state = Term::STATE_ACTIVE;
            $model->parentId = $parentId;
            if (!$model->save())
                $this->result->fail(ERROR_HANDLING_DB, 'save category failed');
            else
            {
                if ($model->parentId)
                {
                    $relation = TermHierarchy::model()->findByAttributes(array('term_id'=>$model->id));
                    if (!is_object($relation))
                    {
                        $relation = new TermHierarchy;
                        $relation->term_id = $model->id;
                    }
                    $relation->parent_id = $model->parentId;
                    if (!$relation->save())
                    {
                        Yii::log(CVarDumper::dumpAsString($relation->getErrors()), CLogger::LEVEL_ERROR);
                    }
                }
            }       
        }
    }
    
    protected function findNextOrder($parentId, $term)
    {
        $criteria = new CDbCriteria;
        $criteria->order = 't.ordering DESC';
        if ($parentId > 0)
        {
            $criteria->join = 'INNER JOIN '.SITE_TABLE_PREFIX.'taxonomy_term_hierarchy th ON th.term_id = t.id';
            $criteria->compare('th.parent_id', $parentId);
        }
        else
        {
            $criteria->compare('t.v_id', $term->v_id);
            $criteria->addCondition('t.id NOT IN (SELECT term_id FROM '.SITE_TABLE_PREFIX.'taxonomy_term_hierarchy)');
        }
        $orderModel = Term::model()->find($criteria);
        return is_object($orderModel) ? (int) $orderModel->ordering : 0;
    }
}